package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public R remove(Long id) {
        //添加查询条件,根据分类id进行删除
        //查询当前分类是否关联菜品,如果已经关联,抛出一个业务异常
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(Dish::getCategoryId, id);
        int count = dishMapper.selectCount(dishQueryWrapper);
        if (count > 0) {
            //已经关联菜品,抛出一个业务异常
            return R.error("当前菜品关联菜品,不能删除!");
        }

        LambdaQueryWrapper<Setmeal> slqw = new LambdaQueryWrapper<>();
        slqw.eq(Setmeal::getCategoryId, id);
        count = setmealMapper.selectCount(slqw);
        if (count > 0) {
            //已经关联套餐,抛出一个业务异常
            return R.error("当前菜品关联套餐,不能删除!");
        }

        int i = categoryMapper.deleteById(id);
        return i > 0 ? R.success("删除分类信息成功") : R.error("删除分类信息失败");
    }
}
